package com.edu.hre.common.runable;

import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import com.edu.hre.common.email.EMailObject;
import com.edu.hre.common.email.EMailSender;
import com.edu.hre.common.utils.BeanFinder;
import com.edu.hre.common.utils.CommonUtils;
import com.edu.hre.common.utils.ServerConfig;
import com.edu.hre.db.pojo.HreEmployee;
import com.edu.hre.db.pojo.HreSubunit;
import com.edu.hre.db.service.BaseService;
import com.edu.hre.db.utils.Compare;

public class NotifyEMailSurvey implements Runnable {

	private String url;
	private int unitId; 
	private static final ServerConfig serverConfig = BeanFinder.getBean(ServerConfig.BEAN_NAME, ServerConfig.class);
	private static final BaseService baseService = BeanFinder.getBean(BaseService.BEAN_NAME, BaseService.class);
	private static final EMailSender eMailSender = BeanFinder.getBean(EMailSender.BEAN_NAME, EMailSender.class);
	
	public NotifyEMailSurvey() {
		// TODO Auto-generated constructor stub
	}
	
	public NotifyEMailSurvey(int surveyId, int unitId) {
		this.unitId = unitId;
		this.url = serverConfig.getHostTakeSurvey().replace("@id", surveyId + "");
	}
	
	public void run() {
		List <HreEmployee> listEmps = null;
		if(unitId == 1){
			listEmps = baseService.getPojos("isDeleted", Compare.EQUAL, false, HreEmployee.class);
		} else {
			HreSubunit subunit = baseService.getPojo(unitId, HreSubunit.class);
			List<Integer> listChildId = new ArrayList<Integer>();
			tagId(listChildId, subunit);
			listEmps = baseService.getPojos("workStation", Compare.IN, listChildId.toArray(), HreEmployee.class);
		}
		ArrayList<EMailObject> listEMailObject = new ArrayList<EMailObject>();
		int count = listEmps == null ? 0 : listEmps.size();
		for(int i = 0; i < count; i ++){
			try {
				HreEmployee tmp = listEmps.get(i);
				EMailObject obj = new EMailObject();
				if(StringUtils.isNotBlank(tmp.getEmpWorkEmail())){
					obj.setAddress(tmp.getEmpWorkEmail());
				} else if(StringUtils.isNotBlank(tmp.getEmpOthEmail())){
					obj.setAddress(tmp.getEmpOthEmail());
				}
				if(StringUtils.isNotBlank(obj.getAddress())){
					obj.setHTMLStyle(false);
					obj.setSubject("Thư mời tham gia chương trình khảo sát");
					String content = serverConfig.getSurveyNotifyMessage().replace("@name", tmp.getEmpFirstname()).replace("@url", this.url);
					content += "\n" + serverConfig.getDefaultEmailSignature();
					obj.setContent(content);
					listEMailObject.add(obj);
				}
			} catch (Exception e) {
				CommonUtils.println(e.getMessage());
			}
		}
		eMailSender.sendMail(listEMailObject);
	}
	
	private void tagId(List<Integer> listChildId, HreSubunit subunit){
		listChildId.add(subunit.getId());
		List<HreSubunit> listChilds = baseService.getPojos("parentId", Compare.EQUAL, subunit.getId(), HreSubunit.class);
		for(int i = 0; listChilds != null && i < listChilds.size(); i ++){
			HreSubunit tmp = listChilds.get(i); 
			tagId(listChildId, tmp);
		}
	}
}
